<template>
    <el-card class="info_cd">
        <el-icon><Checked  /></el-icon>
        <span v-html="infoNum"></span>
    </el-card>
    <el-card shadow="always" class="word_cd" @click="playAudioByWord">
        <!-- 单词提示音 -->
        <audio :src="audioSrc" ref="audio" autoplay />
        <!-- 成功提示音 -->
        <audio src="../audio/菜鸟图库-系统明亮按钮.mp3" ref="succDio" />
        <!-- 失败提示音 -->
        <audio src="../audio/菜鸟图库-s系统-错误.mp3" ref="failDio" />
        <el-text type="primary" class="word_txt">{{ currentWord.chinese }}</el-text>
    </el-card>
    <LogInfo  ref="LogCp" />
    <div class="down_div">
        <el-input 
            v-model="userInput"
            placeholder="请输入正确的英文"
            class="input_txt"
            @keydown.enter="validate"       
            @keydown.left="randomWord"
            @keydown.down="delC"
            @keydown.right="toNextAndValidate"
            @keydown.up="playAudioByWord"
            >
        </el-input> 
    </div>
    <el-card class="sel_cd" ref="selCds">
        <div><el-icon @click="showS" class="show_bt"><Filter /></el-icon></div>
        <div id="selContainer" v-show="showSel">
            <p class="op_p">
                <p class="sel_tit">时间：</p>                
                <p>&nbsp&nbsp&nbsp<input type="date" name="" id="" v-model="beginTime"></p>
                <p style="text-align: center;">to</p>
                <p>&nbsp&nbsp&nbsp<input type="date" name="" id="" v-model="endTime"></p>
            </p>
            <p class="op_p">
                <span class="sel_tit">录入人：</span>
                <select name="" id="selAuthor" v-model="selAuthor">
                    <option value="全部">全部</option>
                    <option v-for="e in userArr" :value="e.id">{{ e.username }}</option>
                </select>
            </p>
            <p class="op_p">
                <span class="sel_tit">分类:</span>
                <select name="" id="selType" v-model="selType">
                    <option value="全部">全部</option>
                    <option v-for="e in typeArr" :value="e">{{ e }}</option>
                </select>
            </p>
        </div>
    </el-card>
        

</template>
<script setup>
    import { reactive,ref,computed,toRef,onMounted,nextTick,watchEffect} from 'vue';
    import { useRouter } from 'vue-router';
    import LogInfo from './LogInfo.vue';
    import { ElMessage } from 'element-plus'
    import axios from '../../config/axios';
    let trueNum = ref(0);
    let falseNum = ref(0);
    let infoNum = computed(()=>`<font color='red'>${falseNum.value}</font>:<font color='purple'>${trueNum.value}</font>`);
    let userInput = ref('');
    let LogCp = ref('');
    let router = useRouter();
    let beginTime = ref('');
    let endTime = ref('');
    let selAuthor = ref('全部');
    let selType = ref('全部');
    let showSel = ref(false);
    let selCds = ref(null);
    let typeArr = ref([]);
    let userArr = ref([]);
    let audioStr = ref('');
    let audioSrc = computed(()=>`https://fanyi.sogou.com/reventondc/synthesis?text=${audioStr.value}&speed=1&lang=zh-CHS&from=translateweb&speaker=6`);
    let audio = ref(null);
    let succDio = ref(null);
    let failDio = ref(null);
    let result;
    let errContinNum = 0;

    
    //删除当前单词
    function delC(){
        result = result.filter(e=>e.id !== currentWord.value.id);
        console.log(`词组：${currentWord.value.chinese}-${currentWord.value.english}已删除，剩余${result.length}个单词`);
        LogCp.value.appendLog(`词组：${currentWord.value.chinese}-${currentWord.value.english}已删除，剩余${result.length}个单词`);
        randomWord();
    }
    //验证当前单词并删除
    function toNextAndValidate(){
        let id = currentWord.value.id;
        validate();
        if(id != currentWord.value.id){
            result = result.filter(e=>e.id !== currentWord.value.id);
            LogCp.value.appendLog(`还剩 ${result.length} 个单词`)
        }
    }

    function playAudioByWord(){
        audioStr.value = currentWord.value.english;
        audio.value.play();
    }

    //展示/关闭菜单
    function showS(){
        showSel.value = !showSel.value;
    }
   
    //单词数组
    let wordArr = reactive([
        {chinese:"你好",english:"hello"}
    ]);
    
    
    
    //当前单词
    let currentWord = ref(
        {chinese:"现在没有数据",english:"现在没有数据"},
    )

    //随机切换
    function randomWord(){
        if(result == null || result.length == 0){
            return currentWord.value = {
                chinese:"当前没有单词",
                english:"当前没有单词"
            }    
        }
        currentWord.value = result[Math.floor(Math.random()*result.length)];
    }

    //验证是否正确
    function validate(){
        if(userInput.value === currentWord.value.english){
            succDio.value.play();
            playAudioByWord();
            errContinNum = 0;
            ElMessage.success('回答正确');
            trueNum.value ++;
            LogCp.value.appendLog(`正确！${currentWord.value.english}`);
            randomWord();
        }else{
            failDio.value.play();
            playAudioByWord();
            errContinNum++;
            ElMessage.warning('回答错误');
            falseNum.value ++;
            LogCp.value.appendLog(`错误！${errContinNum>1?currentWord.value.english:''}`,true);
        }
        
        userInput.value = '';
    }

    //请求所有单词
    function getAllWord(){
        axios.get('/word').then(res=>{
            if(res.data.result){
                LogCp.value.appendLog(`一共获取到${res.data.data.length}个词组`)
                console.log("单词列表",res);
                wordArr = reactive(res.data.data);
                result = wordArr;
                randomWord();
                getAllType();
                getAllUser();
            }else{
                ElMessage.warning(res.data.msg);
                if(res.data.msg == 'token过期了'){
                    router.push('/login');
                }
            }
        })
    }

    //查询所有分类
    function getAllType(){
        typeArr.value = [];
        wordArr.forEach(e=>{
            if(!typeArr.value.includes(e.classType)){
                typeArr.value.push(e.classType);
            }
        })
    }
    
    function getAllUser(){
        axios.get('/user').then(res=>{
            if (res.data.result) {
                console.log("用户信息列表获取成功");
                userArr.value = res.data.data
            }else{
                ElMessage.warning('在获取用户信息列表时出现异常')
                console.log(res.data);
            }
        }).catch(err=>{
            ElMessage.warning('在获取用户信息列表时出现异常2')
            console.log(err);
        })
    }

    onMounted(()=>{
        getAllWord();
        LogCp.value.appendLog(`<p>挂载完毕，开始测验吧！</p>`);
        audioStr.value = '挂载完成，开始测验吧';
    })

    
    //过滤结果
    watchEffect(()=>{
        result = wordArr;
        if(selAuthor.value != '全部'){
            result = result.filter(e=> e.authorId == selAuthor.value);
        };
        if(selType.value != '全部'){
            result = result.filter(e=> e.classType == selType.value);
        }
        if(beginTime.value){
            result = result.filter(e=> e.createdAt > beginTime.value);
        }
        if (endTime.value) {
            result = result.filter(e=> e.createdAt < endTime.value);
        }
        ElMessage.success(`找到${result.length}个单词`);
        nextTick(()=>LogCp.value.appendLog(`找到${result.length}个单词`));

        nextTick(()=>randomWord());

        console.log("过滤结束",result.length);
    },{
        lazy:true
    })
</script>
<style scoped>
.op_p{
    margin: 15px auto;
    user-select: none;
}

.sel_cd{
    width: auto;
    position: fixed;
    left: 1vw;
    top: 39vh;
    transition:width 1s;
}
.word_cd{
    width: 50vw;
    max-width: 500px;
    margin: auto;
    text-align: center;
    height: 40vh;
    background-color: rgb(255, 214, 200);
}
.word_cd:hover{
    cursor: pointer;
}
.show_bt:hover{
    cursor: pointer;
}
.word_txt{
    display: inline-block;
    font-size: 39px;
    font-family: '幼圆';
    margin-top: 20vh;
    transform: translateY(-80%);
    letter-spacing: 2px;
}
.info_cd{
    width: 100px;
    text-align: center;
    font-size: 23px;
    letter-spacing: 4px;
    user-select: none;
    background-color: rgba(217, 220, 42, 0.664);
}
.input_txt{
    width: 70vh;
    min-width: 300px;
    margin: 10vh auto;
    height: 70px;
    font-size: 30px;
}
.down_div{
    text-align: center;
}
</style>